using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;

namespace WindowsUserControl.Dialogs
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="connStr"></param>
    public delegate void NewDatabaseConnection(string connStr);

    /// <summary>
    /// 
    /// </summary>
    public partial class NewDbConnectionDialog : Form
    {

        private System.Collections.Hashtable ht_Connections;    // map server.db to connectionstring

        /// <summary></summary>
        public event NewDatabaseConnection NewDatabaseConnectionEvent;

        #region init
        /// <summary></summary>
        public NewDbConnectionDialog()
        {
            InitializeComponent();
            this.ht_Connections = new System.Collections.Hashtable();
        }

        private void NewDbConnectionDialog_Load(object sender, EventArgs e)
        {
            this.populateAuthenticationTypes();
            this.populateExistingConnections();
        }

        private void populateExistingConnections()
        {
            this.cbo_Servers.Items.Clear();
            string[] connStrs = StringUtil.Split(System.Configuration.ConfigurationManager.AppSettings.Get("ConnectionStore"));
            if (connStrs != null && connStrs.Length > 0)
            {
                for (int i = 0; i < connStrs.Length; i++)
                {
                    string host = DbConnUtil.GetHost(connStrs[i]);
                    string db = DbConnUtil.GetDatabaseName(connStrs[i]);
                    string key = host + "." + db;
                    if (!this.ht_Connections.Contains(key))
                    {
                        this.ht_Connections.Add(key, connStrs[i]);
                        this.cbo_Servers.Items.Add(key);
                    }
                }
                this.cbo_Servers.SelectedIndex = 0;
            }
        }

        private void populateAuthenticationTypes()
        {
            this.cbo_AuthTypes.Items.Clear();
            this.cbo_AuthTypes.Items.Add("Windows Authentication");
            this.cbo_AuthTypes.Items.Add("SQL Server Authentication");
            this.cbo_AuthTypes.SelectedIndex = 0;
        }
        #endregion

        #region set prop
        /// <summary></summary>
        public DataProviderType Provider
        {
            set
            {
                if (value == DataProviderType.MSSQL)
                {
                    this.rd_MSSQL.Checked = true;
                    this.rd_Oracle.Checked = false;
                    this.cbo_AuthTypes.SelectedIndex = 0;
                    this.txt_UserName.Text = "SA";
                }
                else
                {
                    this.rd_MSSQL.Checked = false;
                    this.rd_Oracle.Checked = true;
                    this.cbo_AuthTypes.SelectedIndex = 1;
                    this.txt_UserName.Text = "SYSTEM";
                }
            }
        }
        #endregion

        private void cbo_AuthTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbo_AuthTypes.SelectedIndex == 0)
            {
                this.txt_UserName.Text = Environment.UserDomainName + "\\" + Environment.UserName;
                this.txt_Password.Text = "";
                this.lbl_UserName.Enabled = false;
                this.lbl_Password.Enabled = false;
                this.txt_UserName.Enabled = false;
                this.txt_Password.Enabled = false;
            }
            else if (this.cbo_AuthTypes.SelectedIndex == 1)
            {
                this.txt_UserName.Text = "sa";
                this.txt_Password.Text = "";
                this.lbl_UserName.Enabled = true;
                this.lbl_Password.Enabled = true;
                this.txt_UserName.Enabled = true;
                this.txt_Password.Enabled = true;
            }
        }

        private void cbo_Servers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbo_Servers.SelectedIndex >= 0)
            {
                string key = this.cbo_Servers.SelectedItem.ToString();
                string connStr = (string)this.ht_Connections[key];
                AuthenticationType authType = DbConnUtil.GetAuthenticationType(connStr);
                switch (authType)
                {
                    case AuthenticationType.WindowsAuthentication:
                        this.cbo_AuthTypes.SelectedIndex = 0;
                        this.lbl_UserName.Enabled = false;
                        this.lbl_Password.Enabled = false;
                        this.txt_UserName.Enabled = false;
                        this.txt_Password.Enabled = false;
                        break;
                    case AuthenticationType.SQLServerAuthentication:
                        this.cbo_AuthTypes.SelectedIndex = 1;
                        this.lbl_UserName.Enabled = true;
                        this.lbl_Password.Enabled = true;
                        this.txt_UserName.Enabled = true;
                        this.txt_Password.Enabled = true;
                        break;
                    default:
                        break;
                }
                this.txt_UserName.Text = DbConnUtil.GetUserID(connStr);
                this.txt_Password.Text = DbConnUtil.GetPassword(connStr);
            }
        }

        private void btn_Connect_Click(object sender, EventArgs e)
        {
            string dataSrc = string.Empty;
            string dbName = string.Empty;
            AuthenticationType authType = AuthenticationType.WindowsAuthentication;
            string uid = string.Empty;
            string pwd = string.Empty;

            if (this.cbo_Servers.SelectedIndex > 0)
            {
                string key = this.cbo_Servers.SelectedItem.ToString();
                string connStr = (string)this.ht_Connections[key];
                dataSrc = DbConnUtil.GetHost(connStr);
                dbName = DbConnUtil.GetDatabaseName(connStr);
            }
            else
            {
                dataSrc = this.cbo_Servers.Text;
            }
            if (this.cbo_AuthTypes.SelectedIndex == 1)
            {
                authType = AuthenticationType.SQLServerAuthentication;
            }
            if (authType == AuthenticationType.SQLServerAuthentication)
            {
                uid = this.txt_UserName.Text;
                pwd = this.txt_Password.Text;
            }
            try
            {
                string connStr; // = DbConnUtil.BuildConnectionString(serverName, instanceName, dbName, authType, uid, pwd);
                if (this.rd_MSSQL.Checked)
                {
                    dbName = this.cbo_Dbs.Text;
                    connStr = "Data source=" + dataSrc + ";Database=" + dbName + ";";
                    if (authType == AuthenticationType.WindowsAuthentication)
                    {
                        connStr += "Integrated security=true;";
                    }
                    else
                    {
                        connStr += "User id=" + uid + ";Password=" + pwd + ";";
                    }
                }
                else
                {
                    connStr = "Data source=" + dataSrc + ";";
                    if (authType == AuthenticationType.WindowsAuthentication)
                    {
                        connStr += "Integrated security=true;";
                    }
                    else
                    {
                        connStr += "User id=" + uid + ";Password=" + pwd + ";";
                    }
                }
                
                if (this.NewDatabaseConnectionEvent != null)
                {
                    this.NewDatabaseConnectionEvent(connStr);
                }
                this.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Source);
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void rd_MSSQL_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rd_MSSQL.Checked)
            {
                this.cbo_Dbs.Enabled = true;
            }
            else
            {
                this.cbo_Dbs.Enabled = false;
            }
        }

        private void rd_Oracle_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rd_MSSQL.Checked)
            {
                this.cbo_Dbs.Enabled = true;
            }
            else
            {
                this.cbo_Dbs.Enabled = false;
            }
        }

        private void PopulateDatabases(string connStr)
        {

        }
    }
}